import HeaderComponent from "@/components/HeaderComponent/HeaderComponent";

import { Input, Toast, InfiniteScroll, Popover } from "antd-mobile";
import { FileOutline } from "antd-mobile-icons";
import InfiniteScrollContent from "@/components/InfiniteScrollContentComponent/InfiniteScrollContentComponent";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { getData, orderBuy, getBuyList } from "@/api/module/STC";
import { CenterPopupComponent } from "@/components/CenterPopupComponent/CenterPopupComponent";
import { getApiToken } from "@/api/module/U2U";
import { useNavigate } from "react-router-dom";
import Styles from "./Buy.module.less";
import { useAppSelector } from "@/hooks/useAppSelector";
const AssetsComponent: FC<{
  data: Awaited<ReturnType<typeof getData>>["data"];
}> = ({ data }) => {
  const { t } = useTranslation();
  return (
    <div className="mt-4">
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-4 px-4 rounded-xl"></div>
      <div className="value text-white-1 py-12 px-5 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-center">
        <span className="opacity-50">{t("highestMatchingPrice")}</span>
        <span className="ml-4 font-bold text-2xl">${data.price}</span>
      </div>
    </div>
  );
};
const FormComponent: FC<{
  data: Awaited<ReturnType<typeof getData>>["data"];
}> = ({ data }) => {
  const { t } = useTranslation();
  const [value, setValue] = useState("");
  const [password, setPassword] = useState("");
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const reqOrder = async () => {
    try {
      const res = await orderBuy({
        amount: value,
        APITOKEN: APIToken,
        currency: "GPB",
        password: password,
      });
      console.log(res);
      setAPIToken("");

      Toast.show({
        content: res.msg,
      });
      if (res.code == 0) {
        setValue("");
        setPassword("");
        // dispatch(fetchUserInfo());
      }
    } catch (error) {
      setAPIToken("");
    }
  };

  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState("");
  const reqApiToken = async () => {
    try {
      if (!value) {
        Toast.show({
          content: t("enterCompleteInformation"),
        });
        return;
      }
      // if (!password) {
      //   Toast.show({
      //     content: '请输入2FA OTP',
      //   });
      //   return;
      // }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }

      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div
      className="mt-4"
      style={{
        fontSize: "95%",
      }}
    >
      <div className="cash">
        <div>{t("unit")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={value}
          onChange={(val) => {
            setValue(val);
          }}
        />
        <div className="mt-2 opacity-50 text-xs grid grid-cols-3">
          {/* <span>
            {t("minimum")}: {data.min_amount}
          </span>
          <span>
            {t("highest")}: {data.max_amount}
          </span> */}
          <span>
            {t("banlance")}: {userInfo.GBJ.balance}
          </span>
        </div>
        {/* <div className="mt-4 opacity-50 text-xs grid grid-cols-3">
          <span>
            {t("hangingForSale")}: {data.amount_on_sale}
          </span>
          <span>
            {t("matchedAlready")}: {data.amount_macthed}
          </span>
        </div> */}
      </div>
      <div className="password mt-4">
        <div>{t("secondaryPassword")}</div>
        <Input
          type="password"
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={password}
          onChange={(val) => {
            setPassword(val);
          }}
        />
      </div>
      <div
        onClick={reqApiToken}
        className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
      >
        {t("buy")}
      </div>
      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title="buy"
        content={`${t("buy")}: ${value}${t("SimuDou")}`}
        onClick={() => reqOrder()}
      />
    </div>
  );
};

const LogsComponent = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [active, setActive] = useState(0);
  const tabList = ["myCurrentBuyList"];
  const [data, setData] = useState<
    Awaited<ReturnType<typeof getSaleList>>["data"]["list_data"]
  >([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  async function loadMore() {
    const res = await getBuyList({
      page: page + "",
    });
    setPage((val) => val + 1);
    // const append2 = await Promise.resolve(append);
    setData((val) => [...val, ...res.data.list_data]);
    setHasMore(+res.data.page_on < res.data.total_page);
  }
  return (
    <div className="mt-4">
      <div className="flex justify-between items-center">
        <div className="tab flex">
          {tabList.map((item, index) => {
            return (
              <div
                onClick={() => setActive(index)}
                key={item}
                className={`mr-4 ${active == index ? Styles["active"] : ""}`}
              >
                {t(item)}
              </div>
            );
          })}
        </div>
        {/* 
        <div>
          <Popover
            style={{
              // @ts-ignore
              "--background": "#000",
            }}
            content={
              <div className="text-white-1 px-4">
                <div
                  onClick={() => navigate("/STCRecord/buy")}
                  className="py-2 border-b"
                >
                  {t("STCBuyRecord")}
                </div>
                <div
                  onClick={() => navigate("/STCRecord/sell")}
                  className="py-2"
                >
                  {t("STCSellRecord")}
                </div>
              </div>
            }
            trigger="click"
            placement="bottom"
            defaultVisible={false}
          >
            <FileOutline color="#E99434" />
          </Popover>
        </div> */}
      </div>
      <div className="logs mt-6 text-sm">
        <div className="text-white-1 bg-bg-1 mb-4 rounded-lg p-4 ">
          {active == 0 ? (
            <div>
              <div className="logs-tab-title flex justify-between items-center ">
                <div className="w-2/5">{t("date")}</div>
                <div className="w-1/5">{t("type")}</div>
                <div className="w-1/5">{t("amount")}</div>
                <div className="w-1/5">{t("turnover")}</div>
              </div>
              <div className="logs-tab-content max-h-56 overflow-y-scroll">
                {data.map((item) => (
                  <div
                    key={item.order_id}
                    className="flex justify-between items-center py-2"
                  >
                    <div className="w-2/5">{item.create_time}</div>
                    <div className="w-1/5">
                      {item.currency === "GBJ" ? "RWB" : item.currency}
                    </div>
                    <div className="w-1/5">{item.amount}</div>
                    <div className="w-1/5">{item.amount_matched}</div>
                  </div>
                ))}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                  <InfiniteScrollContent hasMore={hasMore} />
                </InfiniteScroll>
              </div>
            </div>
          ) : (
            <div className="text-center">
              <div className="logs-tab-title flex justify-between items-center ">
                <div className="w-1/2">{t("price")}</div>
                <div className="w-1/2">{t("num")}</div>
              </div>
              <div className="logs-tab-content max-h-56 overflow-y-scroll">
                {data.map((item) => (
                  <div
                    key={item.order_id}
                    className="flex justify-between items-center py-2"
                  >
                    <div className="w-1/2">{item.price}</div>
                    <div className="w-1/2">{item.amount}</div>
                  </div>
                ))}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                  <InfiniteScrollContent hasMore={hasMore} />
                </InfiniteScroll>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default function DigitalVoucherCenter() {
  const [data, setData] = useState<Awaited<ReturnType<typeof getData>>["data"]>(
    {
      price: 0,
      balance: 0,
      min_amount: 0,
      max_amount: 0,
      amount_macthed: 0,
      amount_macthed_market: 0,
      amount_on_sale: 0,
    }
  );
  const reqData = async () => {
    const res = await getData();
    setData(res.data);
  };
  useEffect(() => {
    reqData();
  }, []);
  return (
    <div className="text-white-1 px-4">
      <HeaderComponent
        title="buy"
        centerStyle={{
          fontSize: "18px",
        }}
      />
      <AssetsComponent data={data} />
      <FormComponent data={data} />
      <LogsComponent />
    </div>
  );
}
